package com.aboo.es.service;

import com.aboo.es.dao.MovieDAO;
import com.aboo.es.vo.Movie;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class MovieService {

    @Resource
    private MovieDAO movieDAO;

    public void saveMovie(String id, String name, String desc) {
        Movie movie = new Movie();
        movie.setId(id);
        movie.setName(name);
        movie.setDesc(desc);
        movie.setCreatedDate(new Date());
        movieDAO.save(movie);
    }

    public Movie getById(String id) {
        Optional<Movie> optional = movieDAO.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }

        return null;
    }

    public List<Movie> getAll() {
        List<Movie> list = new ArrayList<>(16);
        Iterable<Movie> iterable = movieDAO.findAll();
        iterable.forEach(list::add);

        iterable.forEach(list::add);

        return list;
    }

    public void updateMovie(String id, String name, String desc) {
        Movie movie = new Movie();
        movie.setId(id);
        movie.setName(name);
        movie.setDesc(desc);
        movieDAO.save(movie);
    }

    public void deleteById(String id) {
        movieDAO.deleteById(id);
    }

    public List<Movie> getByName(String name) {
        List<Movie> list = movieDAO.findByNameLike(name);
        return list;
    }

    public Page<Movie> findByKey(String key, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return movieDAO.findByNameOrDescLike(key, key, pageable);
    }

}
